import { MaterialType, type MaterialTypeKeys } from '../types'

// 媒体上传类型列表
export const materialAcceptList = (
  t: (key: string) => string
): {
  label: string;
  name: any;
  accept: string;
  display: boolean;
}[] => {
  return [
    { label: t("message.type.text"), name: MaterialType.TEXT, accept: ".txt", display: true },
    {
      label: t("message.type.image"),
      name: MaterialType.IMAGE,
      accept: ".jpg,.png,.jpeg",
      display: true,
    },
    { label: t("message.type.video"), name: MaterialType.VIDEO, accept: "video/*", display: true },
    { label: t("message.type.audio"), name: MaterialType.AUDIO, accept: "audio/*", display: true },
    { label: t("message.type.ptt"), name: MaterialType.PTT, accept: ".oga", display: true },
    { label: "Sticker", name: MaterialType.STICKER, accept: ".webp", display: true },
    { label: "Gif", name: MaterialType.GIF, accept: ".mp4", display: true },
    { label: t("message.type.document"), name: MaterialType.FILE, accept: "*/*", display: true },
    { label: t("message.type.vcard"), name: MaterialType.CARD, accept: ".txt", display: true },
    { label: t("common.nickname"), name: MaterialType.NICKNAME, accept: ".txt", display: false },
    { label: t("common.avatar"), name: MaterialType.AVATAR, accept: "image/*", display: false },
    { label: t("message.type.url"), name: MaterialType.LINK, accept: ".txt", display: true },
    {
      label: t("message.type.merchant_url"),
      name: MaterialType.MERCHANT_LINK,
      accept: ".txt",
      display: true,
    },
    {
      label: t("common.imageTextTemplate"),
      name: MaterialType.IMAGETEXTTEMPLATE,
      accept: ".txt",
      display: true,
    },
    { label: t("message.type.poll"), name: MaterialType.POLL, accept: ".txt", display: true },
  ];
};

// 根据素材类型获取上传类型
export const getMaterialUploadAccept = (
  materialType: MaterialTypeKeys,
  t: (key: string) => string
) => {
  const item = materialAcceptList(t).find((item) => item.name === materialType);
  return item?.accept || "*/*";
};

// 获取文件扩展名
export const getFileExt = (fileName: string): string => {
  if (!fileName) return '';
  const lastDotIndex = fileName.lastIndexOf('.');
  return lastDotIndex !== -1 ? fileName.substring(lastDotIndex + 1).toLowerCase() : '';
};

// 文件大小格式化
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 验证文件类型
export const validateFileType = (file: File, accept: string): boolean => {
  if (accept === '*/*') return true;
  
  const acceptTypes = accept.split(',').map(type => type.trim());
  const fileExtension = '.' + getFileExt(file.name);
  const fileType = file.type;
  
  return acceptTypes.some(acceptType => {
    if (acceptType.startsWith('.')) {
      return fileExtension === acceptType;
    } else if (acceptType.includes('/*')) {
      const mainType = acceptType.split('/')[0];
      return fileType.startsWith(mainType);
    } else {
      return fileType === acceptType;
    }
  });
};

// 验证文件大小
export const validateFileSize = (file: File, maxSize: number = 5 * 1024 * 1024): boolean => {
  return file.size <= maxSize;
};

// 生成唯一ID
export const generateId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 防抖函数
export const debounce = <T extends (...args: any[]) => any>(
  func: T,
  wait: number
): ((...args: Parameters<T>) => void) => {
  let timeout: number;
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(null, args), wait);
  };
};

// 节流函数
export const throttle = <T extends (...args: any[]) => any>(
  func: T,
  limit: number
): ((...args: Parameters<T>) => void) => {
  let inThrottle: boolean;
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func.apply(null, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
};

// 深拷贝
export const deepClone = <T>(obj: T): T => {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj.getTime()) as any;
  if (obj instanceof Array) return obj.map(item => deepClone(item)) as any;
  if (typeof obj === 'object') {
    const clonedObj = {} as any;
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
  return obj;
};